package com.cebbank.sz.cebtemplate.utils;

/**
 * 获取唯一ID
 * @author sucz
 * @create 2019/12/6 14:24
 */
public class SnowFlakeUtil {

    /**
     * 私有静态内部类
     */
    private static class SnowFlake {

        /**
         * 内部类对象（单例模式）
         */
        private static final SnowFlake SNOW_FLAKE = new SnowFlake();

        /**
         * 自定义起始时间戳 2019-12-01 00:00:00
         */
        private static final long START_TIMESTAMP = 1575129600000L;

        // 每一部分占用的位数
        /**
         * 序列号占用位数
         */
        private static final long SEQUENCE_BIT = 12;

        /**
         * 机器标识占用位数
         */
        private static final long MACHINE_BIT = 5;

        /**
         * 数据中心占用位数
         */
        private static final long DATACENTER_BIT = 5;

        // 每一部分最大值
        /**
         * 序列号
         */
        private static final long SEQUENCE_MAX_NUM = -1L ^ (-1L << DATACENTER_BIT);

        /**
         * 机器标识
         */
        private static final long MACHINE_MAX_NUM = -1L ^ (-1L << MACHINE_BIT);

        /**
         * 数据中心
         */
        private static final long DATACENTER_MAX_NUM = -1L ^ (-1L << SEQUENCE_BIT);

        // 每一部分向左的位移
        /**
         * 机器标识
         */
        private static final long MACHINE_LEFT = SEQUENCE_BIT;

        /**
         * 数据中心
         */
        private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;

        /**
         * 时间
         */
        private static final long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

        /**
         * 数据中心ID
         */
        private long dataCenterId;

        /**
         * 机器标识ID
         */
        private long machineId;

        /**
         * 序列号
         */
        private long sequence = 0L;

        /**
         * 上一次时间戳
         */
        private long lastTimestamp = -1L;

        /**
         * 产生下一个ID：自定义数据中心ID、机器标识ID
         * @param dataCenterId 数据中心ID
         * @param machineId 机器标识ID
         * @return
         */
        private synchronized String generateNextId(long dataCenterId, long machineId) {
            if (dataCenterId > DATACENTER_MAX_NUM || dataCenterId < 0) {
                throw new IllegalArgumentException("dataCenterId can't be greater than DATACENTER_MAX_NUM.");
            }
            if (machineId > MACHINE_MAX_NUM || machineId < 0) {
                throw new IllegalArgumentException("machineId can't be greater than MACHINE_MAX_NUM or less.");
            }
            this.dataCenterId = dataCenterId;
            this.machineId = machineId;
            return generateNextId();
        }

        /**
         * 产生下一个ID
         * @return
         */
        private synchronized String generateNextId() {
            long currentTimestamp = getNewTimestamp();
            if (currentTimestamp < lastTimestamp) {
                throw new RuntimeException("Clock moved backwards. Refusing to generate id.");
            }

            if (currentTimestamp == lastTimestamp) {
                // 当前调用和上一次调用落在相同毫秒内，通过第三部分序列号自增来判断唯一
                sequence = (sequence + 1) & SEQUENCE_MAX_NUM;
                // 同一毫秒的序列数已经达到最大，等待下一个毫秒
                if (sequence == 0L) {
                    currentTimestamp = getNextMill();
                }
            } else {
                // 当前调用和上一次调用落不在同一个毫秒内，序列号置为0
                sequence = 0L;
            }

            lastTimestamp = currentTimestamp;
            long nextId = (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT
                    | dataCenterId << DATACENTER_LEFT
                    | machineId << MACHINE_LEFT
                    | sequence;

            return String.valueOf(nextId);
        }

        /**
         * 获取当前毫秒
         * @return
         */
        private long getNewTimestamp() {
            return System.currentTimeMillis();
        }

        /**
         * 获取下一个毫秒
         * @return
         */
        private long getNextMill() {
            long mill = getNewTimestamp();
            while (mill <= lastTimestamp) {
                mill = getNewTimestamp();
            }
            return mill;
        }
    }

    /**
     * 获取全局唯一ID
     * @return
     */
    public static String nextId() {
        return SnowFlake.SNOW_FLAKE.generateNextId();
    }

    /**
     * 获取全局唯一ID
     * @param dataCenterId 自定义数据中心ID
     * @param machineId 自定义机器标识ID
     * @return
     */
    public static String nextId(long dataCenterId, long machineId) {
        return SnowFlake.SNOW_FLAKE.generateNextId(dataCenterId, machineId);
    }

}
